<?php
/**
 * Модераторская панель платежей
 */
class multitender_action_moder_payments extends multitender_action {

    function  __construct() {
        parent::__construct();
        $rights = $this->conf['user']['right'];
        if ($rights<=1) {
    	    $tpl = $this->new_tpl();
    	    $tpl->display("msg_right.tpl");
    	    exit;
        }
        $this->db      = & $this->conf['dbs']['person'];
    }

    function show() {
        $keysubmit = "Фильтр";

        if (!empty($_POST['submit']) && ($_POST['submit']==$keysubmit)) {
            $filter = array();
            if (!empty($_POST['pay_id'])) {
                $filter['pay_id'] = $_POST['pay_id'];
            }
            if (!empty($_POST['inn'])) {
                $filter['inn'] = $_POST['inn'];
            }
        } else {
            $filter = null;
        }

        $bl=$this->new_model("billing");

        $tpl = $this->new_tpl();

        $offset=((@$_GET['page'] ? $_GET['page'] : 1)-1) * 25; //if ($offset < 0) { $offset=0; }
        $payments = $bl->get_payments_filter($filter, $offset, 25);
        if ($payments) {
            $pays_count = $payments['count']->fields[0];
            unset($payments['count']);

            foreach ($payments as $p) {
                $userids[] = $p['user_id'];
            }
            $us = $this->new_model("users");
            $users = $us->get_user_by_ids($userids);

            foreach ($payments as &$p) {
                if ($users) {
                    foreach($users as $u) {
                        if ($u['Id']==$p['user_id']) {
                            $p['username']=$u['name'];
                        }
                    }
                }
            }
        } else {
            $pays_count = 0;
        }

        $scrol = $this->new_action("scrol");
        $link = $this->conf['pref']['link_base'];
        $scrol->link = $link."action=moder_payments".$scrol->link;

        $scrol->total = Ceil($pays_count/25);
        $tpl->assign('scrol', $scrol->run());
        $offset=($scrol->page-1) * 25;
        $tpl->assign("pay_id", @$filter['pay_id']?$filter['pay_id']:'');
        $tpl->assign("inn", @$filter['inn']?$filter['inn']:'');
        $tpl->assign("payscount", $pays_count);
        $tpl->assign("pays", $payments);
        $tpl->assign("keysubmit", $keysubmit);
        $tpl->assign("right", $this->conf['user']['right']);

        return $tpl->fetch("moder_payments.tpl");
    }

    function acceptpayment() {

        $rights = $this->conf['user']['right'];
        if ($rights<=100) { return "<b>Не достаточно прав</b>"; } 

        $payment_id = & $_GET['payment_id'] ? $_GET['payment_id'] : 0;
        $user_id = & $_GET['user_id'] ? $_GET['user_id'] : 0;
        if (!$payment_id || !$user_id) {
            return false;
            exit;
        }
        $bl = $this->new_model("billing");
        if ($bl->paid($payment_id)) {
            // Отправка оповещения об оплате
            if($this->send_notice($user_id, $payment_id)) {
                return "<b>Оплачен</b>, оповещение отправленно";
            } else {
                return "<b>Оплачен</b>";
            }
        } else {
            return "<b>Ошибка :(</b>";
        }
    }

    // send notice
    function send_notice($user_id, $payment_id) {
        $user_id      = (int) $user_id;
        $joomla_users = 'ten_users';

        if (empty($this->db_joomla)) {
            $this->db_joomla = ADONewConnection($this->conf['db_conf']['joomla']['dsn']);
            $this->db_joomla->Execute('set names utf8');
        }

        $joomla_id = $this->db->GetOne("SELECT joomla_id FROM users WHERE id=$user_id");
        $user_info = $this->db_joomla->GetRow("SELECT username,email FROM $joomla_users WHERE id=$joomla_id");
        if (empty($user_info)) {
            return false;
        }

        require_once $this->conf['libdir'] . "/util_str2.php";
        require_once $this->conf['libdir'] . '/phpmailer/class.phpmailer.php';

        $tpl = $this->new_tpl();
        $tpl->assign('email',  $user_info['email']);
        $tpl->assign('login',  $user_info['username']);
        $tpl->assign('number', $payment_id);
        $content = $tpl->fetch('moder_payments_notice.tpl');

        $mail = new PHPMailer(true);
        try {
            $mail->IsSendmail();
            $mail->CharSet = 'UTF-8';
            $mail->SetFrom($this->conf['email_error_to'], $this->conf['pref']['site_name']);
            $mail->AddAddress($user_info['email'], $user_info['username']);
            $mail->Subject = $this->conf['pref']['site_name'] . ' :: оповещение о поступлении денег';
            $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';
            $mail->MsgHTML($content);
            $mail->Send();
            return true;
        } catch (phpmailerException $e) {
            echo $user_info['email'];
            echo $e->errorMessage(); //Pretty error messages from PHPMailer
        } catch (Exception $e) {
            echo $user_info['email'];
            echo $e->getMessage(); //Boring error messages from anything else!
        }
        return false;
    }

    function run() {
        $this->conf['page_title'] = 'Платежи пользователей';

        $user_id = $this->conf['user']['id'];
        $this->conf['page_joomla_links'][] = '<link rel="stylesheet" href="/templates/mt/css/moder.css" type="text/css"';

        if (!$user_id) {
            $tpl = $this->new_tpl();
            return $tpl->fetch("msg_auth.tpl");
            exit;
        }

        $task = & $_GET['task'] ? $_GET['task'] : "show";

        switch ($task) {
            case 'acceptpayment':
                return $this->acceptpayment();
                break;
            default:
                return $this->show();
                break;
        }
    }
}
